<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
</head>

<body>
    <div class="box">
        <div class="header">
            <div class="title">
                <!-- <button id="tian">+添加商品</button> -->
                <!-- Button trigger modal -->
                <button type="button" id="tian" class="btn btn-primary btn-lg" data-toggle="modal"
                    data-target="#myModal">
                    +添加商品
                </button>

                <!-- Modal -->
                <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                        aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">添加列表</h4>
                            </div>
                            <div class="modal-body">
                                商品名称: <input style="margin-left: 3rem;" type="text" id="goods_name1"><br>
                                商品库存:<input style="margin-left: 3.5rem;" type="text" id="stock1"><br>
                                商品已售:<input style="margin-left: 3.5rem;" type="text" id="sold1"><br>
                                商品价格:<input style="margin-left: 3.5rem;" type="text" id="price1"><br>
                                <div style="list-style: 16px;">
                                    是否上架:
                                    <input style="width: 2rem; height: 2rem; margin-left: 2rem;" type="radio"
                                        name="isOnLine" checked value="1">上架
                                    <input style="width: 2rem; height: 2rem; margin-left: 2rem;" type="radio"
                                        name="isOnLine" value="2" id="">下架
                                </div>

                                图片链接地址:<input type="text" id="Image1"><br>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal"
                                    style=" background-color: red; color: #fff; font-size: 1.5rem; border: none;">关闭</button>
                                <button type="button" id="btn" class="btn btn-primary">添加</button>
                            </div>
                        </div>
                    </div>
                </div>



                <div class="modal fade" id="my" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                        aria-hidden="true">&times;</span></button>
                                <h4 class="modal-title" id="myModalLabel">添加列表</h4>
                            </div>
                            <div class="modal-body">
                                商品名称: <input style="margin-left: 3rem;" type="text" id="goods_name2"><br>
                                商品价格:<input style="margin-left: 3.5rem;" type="text" id="price2"><br>
                                商品库存:<input style="margin-left: 3.5rem;" type="text" id="stock2"><br>
                                商品已售:<input style="margin-left: 3.5rem;" type="text" id="sold2"><br>
                                <div style="list-style: 16px;">
                                    是否上架:
                                    <input style="width: 2rem; height: 2rem; margin-left: 2rem;" type="radio"
                                        name="isOnLine" checked value="1">上架
                                    <input style="width: 2rem; height: 2rem; margin-left: 2rem;" type="radio"
                                        name="isOnLine" value="2" id="">下架
                                </div>

                                图片链接地址:<input type="text" id="Image2"><br>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal"
                                    style=" background-color: red; color: #fff; font-size: 1.5rem; border: none;">取消</button>
                                <button type="button" id="saveBtn" class="btn btn-primary">保存</button>
                            </div>
                        </div>
                    </div>
                </div>

                
            </div>
            <div class="to">
                <span style="padding-left: 8rem; color: #fff;">商品名称:</span> 
                <input type="text" id="search">
                <button id="searchbtn">搜索</button>
            </div>
        </div>
        <div class="content">
            <table border="1" id="table" style="width: 100%; height: 100%;">
                <thead>
                    <tr>
                        <th><input class="chk" type="checkbox" id="all"></th>
                        <th>ID</th>
                        <th>商品</th>
                        <th class="mouseclick">价格</th>
                        <th class="mouseclick">库存</th>
                        <th class="mouseclick">销量</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
                <!-- <img src="http://www.thingjs.com/guide/image/citybuilder/%E5%9B%AD%E5%8C%BA1.png" alt=""> -->
            </table>
            <button id="dels">删除选中</button>
        </div>
    </div>
</body>
<script src="ajax.js"></script>
<script>
    window.onload = function () {
        //显示列表
        getGoodsData()
        // btn.onclick = add
        let addbtn = document.querySelector('#btn')
        addbtn.onclick = addGoodsFun
        //搜索
        // searchbtn.onclick = searchFun
        // .onkeyup = searchFun
        searchbtn.addEventListener('click',searchFun)
        search.addEventListener('keyup',searchFun)
        //保存
        saveBtn.onclick = saveGoods
        //全选
        document.getElementById('all').onchange = allFun
        //删除选中
        document.getElementById('dels').onclick = delsFun
        document.querySelectorAll('.mouseclick')[0].onclick = sortFun
        document.querySelectorAll('.mouseclick')[1].onclick = sortFun
        document.querySelectorAll('.mouseclick')[2].onclick = sortFun
    }

    function allFun() {
        let checkAll = this.checked
        let chk = Array.from(document.getElementsByName('chk'))
        chk.forEach((item) => {
            item.checked = checkAll
        })
    }

    //显示列表
    function getGoodsData() {
        ajax({
            type: 'get',
            url: 'https://liu.zzgoodqc.cn/goods/goodslist',
            success: function (res) {
                console.log(res);
                if (res.code == 200) {
                        rendder(res.data)
                } 
            }
        })
    }
    function rendder(data) {
            if (data.length == 0) {
                document.querySelector('tbody').innerHTML =
                    '<tr><th colspan="8" style="color:#ccc;font-size:23px;">暂无数据</th></tr>'
                return
            }
            // data.sort((a, b) => {
            //     return b.id - a.id
            // })
            // var str = ''
            //     for (let i in data) {
            //         str += `
            //                 <tr>
            //                     <td><input type="checkbox" class='chk' name="chk"
            //                         data-id="${res.data[i].id}"></td>
            //                      <td>${res.data[i].id}</td>
            //                      <td><img src="${res.data[i].img}" alt="">${res.data[i].goods_name}</td>
            //                      <td style="font-weight: bold;">￥${res.data[i].price}</td>
            //                      <td>${res.data[i].stock}</td>
            //                      <td>${res.data[i].sold}</td>
            //                      <td>${getDate(res.data[i].created_at)}</td>  
            //                      <td>
            //                         <button id="bian" onclick='modify(${res.data[i].id})' type="button" 
            //                         class="btn btn-primary btn-lg bianji" data-toggle="modal"
            //                         data-target="#my">编辑</button>
            //                         <button id="de" onclick='del(${res.data[i].id})'>删除</button>
            //                      <td>
            //                 </tr>
            //                 `
            //     }
            //     document.getElementsByTagName('tbody')[0].innerHTML = str

            let html = ''
            data.forEach((item, index) => {
                html += `<tr>
                        <td><input type="checkbox" class='chk' name="chk" data-id="${
                            item.id
                        }"/></td>
                        <td>${item.id}</td>
                        <td><img src="${item.img}">${item.goods_name}</td>
                        <td style="font-weight: bold;">￥${item.price}</td>
                        <td>${item.stock}</td>
                        <td>${item.sold}</td>
                        <td>${getDate(item.created_at)}</td>
                        <td>
                            <a href="#" data-id="${item.id}">编辑</a>
                            <a href="#" data-id="${item.id}">删除</a>
                        </td>
                    </tr>`
            })
            document.querySelector('tbody').innerHTML = html
        }



    //转换成时间
    function getDate(dates) {
        let created_at = new Date(dates)
        return (
            created_at.getFullYear() +
            '-' +
            (created_at.getMonth() + 1) +
            '-' +
            created_at.getDate() +
            ' ' +
            created_at.getHours() +
            ':' +
            created_at.getMinutes() +
            ':' +
            created_at.getSeconds()
        )
    }


    // add()
    //添加
    function addGoodsFun() {
        //声明一个变量 获取数据
        let status = document.querySelector(
            'input[name="isOnLine"]:checked'
        ).value
        let data = {
            goods_name: goods_name1.value,
            stock: stock1.value,
            price: price1.value,
            status: status || 1,
            sold: sold1.value,
            img: Image1.value
        }
        ajax({
            type: 'POST',
            url: 'https://liu.zzgoodqc.cn/goods/add',
            data: data,
            success: function (res) {
                console.log(res);
                getGoodsData()
            }
        })
    }

    //删除
    function del(id) {
        ajax({
            type: 'get',
            url: 'https://liu.zzgoodqc.cn/goods/delete?id=' + id,
            success: function (res) {
                console.log(res);

                var x = confirm("确认删除吗？")                //弹出确认删除弹窗
                if (!x)     //确认删除就是true  取消就是false  这里是取反，所以当取消的时候，就直接返回
                    return;
                window.location.reload()
            }
        })
    }

    // 搜索
    function searchFun() {
        // 获取搜索框的值
        if (event.keyCode == 13 || event.type == 'click') {
            let app = document.querySelector('#search').value
            // console.log(app);
            //获取商品数据
            if (app) {
                ajax({
                    url: 'https://liu.zzgoodqc.cn/goods/search',
                    type: 'post',
                    data: {
                        goods_name:app,
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            console.log(111);
                            getGoodsData(res.data)
                        }
                    },
                })
            }
        }
    }
    //修改
    function modify(id) {
        let status = document.querySelector(
            'input[name="isOnLine"]:checked'
        ).value
        ajax({
            url: 'https://liu.zzgoodqc.cn/goods/detail?id=' + id,
            success: function (res) {
                if (res.code == 200) {
                    thisId = id
                    goods_name2.value = res.data.goods_name
                    stock2.value = res.data.stock
                    price2.value = res.data.price
                    // state.value = res.data.status
                    sold2.value = res.data.sold
                    Image2.value = res.data.img
                    getGoodsData()
                }
            },
        })
    }
    function saveGoods() {
        console.log(123);
        let status1 = document.querySelector(
            'input[name="isOnLine"]:checked'
        ).value
        let data = {
            id: thisId,
            goods_name: goods_name2.value || '小八爪鱼',
            stock: stock2.value || 100,
            price: price2.value || 100,
            status: status1 || 1,
            sold: sold2.value || 100,
            img: Image2.value || 'https://img14.360buyimg.com/n7/jfs/t1/206184/37/26048/63725/62fc9493E51311fa7/c37c6193ac9e62be.jpg'
        }
        console.log(111);
        console.log(data);
        ajax({
            type: 'post',
            url: 'https://liu.zzgoodqc.cn/goods/update',
            data: data,
            success: function (i) {
                getGoodsData()
            },
        })
    }




    //声明变量
    let sortObj = {
        price: 'asc',
        stock: 'asc',
        sold: 'asc',
    }
    //排序
    function sortFun() {
        let data = {
            page: 1,
            limit: 1000,
        }
        if (this.innerHTML == '价格') {
            data.type = 'price'
            data.sort = sortObj.price == 'asc' ? 'desc' : 'asc'
            sortObj.price = data.sort
        }
        if (this.innerHTML == '库存') {
            data.type = 'stock'
            data.sort = sortObj.stock == 'asc' ? 'desc' : 'asc'
            sortObj.stock = data.sort
        }
        if (this.innerHTML == '销量') {
            data.type = 'sold'
            data.sort = sortObj.sold == 'asc' ? 'desc' : 'asc'
            sortObj.sold = data.sort
        }
        ajax({
            url: 'https://liu.zzgoodqc.cn/goods/sort',
            data: data,
            success: function (res) {
               
                    getGoodsData(res.data)
                    console.log(res.data);
            },
        })
    }

    //批量删除
    function delsFun() {
        let checkedObj = Array.from(
            document.querySelectorAll('.chk:checked')
        )
        checkedObj.forEach((item) => {
            let id = item.getAttribute('data-id')
            del(id, item)
        })
    }
    function allFun() {
        let checkAll = this.checked
        let chk = Array.from(document.getElementsByName('chk'))
        chk.forEach((item) => {
            item.checked = checkAll
        })
    }
</script>
<style>
    * {
        padding: 0;
        margin: 0;
    }

    .box {
        width: 100%;
        height: 78.9rem;
        /* background-color: aqua; */
        background: url('http://pic.bizhi360.com/bbpic/97/11097.jpg') no-repeat;
        background-size: 100% 100%;
        /* color: #fff; */
    }

    .title {
        width: 100%;
        height: 6rem;
        /* background-color: aqua; */
        color: #000;
        font-size: 1.8rem;
        display: flex;
        align-items: center;
    }

    .to {
        width: 90%;
        height: 6rem;
        /* background-color: aqua; */
        font-size: 1.9rem;
        display: flex;
        align-items: center;
    }

    .modal-body {
        text-align: center;
        line-height: 5rem;
    }

    .content {
        width: 90%;
        height: 66rem;
        background: url('http://pic.bizhi360.com/bbpic/97/11097.jpg') no-repeat;
        background-size: 100% 100%;
        /* //隐藏水平滚动条 */
        overflow-x: hidden;
        margin: auto;
    }

    table {
        border: 1px solid #fff;
    }

    table input {
        width: 4rem;
        height: 2rem;
    }

    th,
    td {
        text-align: center;
    }

    img {
        width: 20rem;
        height: 10rem;
    }

    input {
        width: 20rem;
        height: 4rem;
    }

    #de {
        width: 6rem;
        height: 3rem;
        background-color: red;
        border: none;
    }

    #searchbtn {
        width: 8rem;
        height: 4rem;
        background-color: deepskyblue;
        border: none;
        margin-left: 1rem;
    }

    #tian {
        margin-left: 8rem;
    }

    #dels {
        margin-top: 20px;
        margin-left: 10px;
        background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
        border: none;
    }
</style>

</html>